extends CharacterBody2D

# 配置参数
@export var move_speed: int = 128       # 每秒移动像素数
@export var grid_size: int = 16        # 网格尺寸（需与地图对齐）

@onready var sprite: AnimatedSprite2D = $AnimatedSprite2D
@onready var ray: RayCast2D = $RayCast2D
@export var bullet_scene : PackedScene # 子弹场景

# 定义一个变量来存储当前播放的动画名称
var current_animation := ""

# 移动方向枚举
enum Direction { UP, DOWN, LEFT, RIGHT }

var is_moving: bool = false
var target_position: Vector2 = Vector2.ZERO

func _ready():
	target_position = position  # 初始位置同步
	add_to_group("player") #添加将 player 加入指定 group 的代码

func _physics_process(delta):
	if !is_moving:
		handle_input()
	else:
		move_towards_target(delta)
	handle_shooting() # 处理射击逻辑

# 输入处理
func handle_input():
	var input_dir := Vector2(
		Input.get_axis("ui_left", "ui_right"),
		Input.get_axis("ui_up", "ui_down")
	)

	if input_dir != Vector2.ZERO:
		attempt_move(input_dir.normalized())

# 尝试移动
func attempt_move(dir: Vector2):
	ray.target_position = dir * grid_size
	ray.force_raycast_update()
	
	if !ray.is_colliding():
		target_position = position + dir * grid_size
		is_moving = true
		update_animation(dir)
	else:
		# 碰撞时播放受阻动画（可选）
		sprite.play("bump")

# 平滑移动
func move_towards_target(delta):
	var move_distance = move_speed * delta
	var move_vector = (target_position - position).normalized() * move_distance
	
	if position.distance_to(target_position) > move_distance:
		position += move_vector
	else:
		position = target_position
		is_moving = false
		sprite.play("idle_" + get_direction_suffix())

# 动画更新
func update_animation(dir: Vector2):
	var anim_suffix := "down"
	
	if dir.x > 0:
		anim_suffix = "right"
	elif dir.x < 0:
		anim_suffix = "left"
	elif dir.y > 0:
		anim_suffix = "down"
	elif dir.y < 0:
		anim_suffix = "up"
	# 构建即将播放的动画名称
	var new_animation = "walk_" + anim_suffix

	# 检查当前动画和即将播放的动画是否不同
	if new_animation != current_animation:
		# 如果不同，则播放新动画
		sprite.play(new_animation)
		# 更新当前动画名称
		current_animation = new_animation
			
func check_interaction():
	var ray = RayCast2D.new()
	ray.target_position = Vector2(grid_size, 0).rotated(rotation)
	if ray.is_colliding():
		var obj = ray.get_collider()
		if obj.has_method("interact"):
			obj.interact()
			
# 获取当前方向后缀
func get_direction_suffix() -> String:
	return sprite.animation.split("_")[1]


func handle_shooting():
	if Input.is_mouse_button_pressed(MOUSE_BUTTON_LEFT):
		var mouse_position = get_viewport().get_mouse_position()
		var shoot_direction = (mouse_position - global_position).normalized()
		shoot(shoot_direction)

func shoot(direction: Vector2):
	var new_bullet = bullet_scene.instantiate()
	new_bullet.global_position = global_position
	new_bullet.velocity = direction * 300 # 子弹速度
	add_child(new_bullet)
